package cn.studyjams.s1.contest.autohello;


import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.support.v4.content.ContextCompat;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.ms.square.android.expandabletextview.ExpandableTextView;
import com.wefika.flowlayout.FlowLayout;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import cn.studyjams.s1.contest.autohello.model.Contact;
import cn.studyjams.s1.contest.autohello.model.Event;
import cn.studyjams.s1.contest.autohello.model.RepeatMode;

public class PreviewEventFragment extends DialogFragment {

    public interface PreviewEventListener {
        void onConfirmSaveEvent();
    }

    PreviewEventListener previewEventListener;

    public PreviewEventFragment() {
        // Required empty public constructor
    }

    @Override
    public void onStart() {
        super.onStart();
        Dialog dialog = getDialog();
        if (dialog != null) {
            DisplayMetrics dm = new DisplayMetrics();
            getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
            dialog.getWindow()
                    .setLayout((int) (dm.widthPixels * 0.85), ViewGroup.LayoutParams.WRAP_CONTENT);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        try {
            previewEventListener = (PreviewEventListener) context;
        } catch (ClassCastException e) {
            throw new ClassCastException(context.toString()
                    + "must implement PreviewEventFragment");
        }
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        String[] colorNames = new String[]{
                getResources().getString(R.string.tomato),
                getResources().getString(R.string.banana),
                getResources().getString(R.string.cucumber),
                getResources().getString(R.string.blue_berry),
                getResources().getString(R.string.grape),
                getResources().getString(R.string.default_color)
        };

        View view = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_preview_event, null);

        Event event = (Event) getArguments().getSerializable("event");

        ExpandableTextView contentTV = (ExpandableTextView) view.findViewById(R.id.expand_text_view);

        TextView smsContentOver160 = (TextView) view.findViewById(R.id.sms_content_over_160);

        TextView datetimeTV = (TextView) view.findViewById(R.id.preview_datetime);
        TextView repeatModeTV = (TextView) view.findViewById(R.id.preview_repeat_mode);
        TextView labelTV = (TextView) view.findViewById(R.id.preview_label);
        TextView colorTV = (TextView) view.findViewById(R.id.preview_color);
        TextView isActiveTV = (TextView) view.findViewById(R.id.preview_is_active);

        FlowLayout phoneContactsHolder = (FlowLayout) view.findViewById(R.id.preview_contact_phone_holder);
        FlowLayout emailContactsHolder = (FlowLayout) view.findViewById(R.id.preview_contact_mail_holder);
        int pCount = 0;
        int eCount = 0;

        if (event != null) {

            Log.d("PreviewEventFragment", event.getIsDelete()+"");

            FlowLayout.LayoutParams layoutParams = new FlowLayout.LayoutParams(
                    FlowLayout.LayoutParams.WRAP_CONTENT,
                    FlowLayout.LayoutParams.WRAP_CONTENT
            );
            layoutParams.setMargins(8, 4, 4, 8);

            // receivers
            for (Contact contact : event.getReceivers()) {
                TextView textView = new TextView(getActivity());
                textView.setLayoutParams(layoutParams);

                textView.setPadding(16, 8, 16, 8);
                textView.setBackground(ContextCompat.getDrawable(getActivity(), R.drawable.arc_rectangle_black_bg));
                switch (contact.getType()) {
                    case 0:
                        textView.setText(contact.getName() + ":" + contact.getPhoneNumber());
                        phoneContactsHolder.addView(textView);
                        pCount++;
                        break;
                    case 1:
                        textView.setText(contact.getName() + ":" + contact.getEmailAddress());
                        emailContactsHolder.addView(textView);
                        eCount++;
                        break;
                    default:
                        break;
                }
            }

            if (pCount == 0) {
                TextView textView = new TextView(getActivity());
                textView.setLayoutParams(layoutParams);

                textView.setPadding(16, 8, 16, 8);
                textView.setBackground(ContextCompat.getDrawable(getActivity(), R.drawable.arc_rectangle_black_bg));
                textView.setText(getString(R.string.none));
                phoneContactsHolder.addView(textView);
            }

            if (eCount == 0) {
                TextView textView = new TextView(getActivity());
                textView.setLayoutParams(layoutParams);

                textView.setPadding(16, 8, 16, 8);
                textView.setBackground(ContextCompat.getDrawable(getActivity(), R.drawable.arc_rectangle_black_bg));
                textView.setText(getString(R.string.none));
                emailContactsHolder.addView(textView);
            }

            // datetime
            String dateTimeStr = event.getDateTime();
            datetimeTV.setText(dateTimeToLocal(dateTimeStr));

            //content
            String content = event.getContent();
            if (content.length() > 160) {
                smsContentOver160.setVisibility(View.VISIBLE);
            } else {
                smsContentOver160.setVisibility(View.GONE);
            }
            contentTV.setText(content);

            //repeat mode
            RepeatMode repeatMode = event.getRepeatMode();

            String repeatStr = "";
            switch (repeatMode.getRepeatType()) {
                case 0:
                    repeatStr += getString(R.string.do_not_repeat);
                    break;
                case 1:
                    repeatStr += getString(R.string.repeat_every_day);
                    break;
                case 2:
                    repeatStr += getString(R.string.repeat_every_week);
                    String weeksStr = repeatMode.getWhichWeeks();
                    String[] whichWeeks = weeksStr.substring(1, weeksStr.length() - 1).split(", ");

                    Map<Integer, String> weekMap = new HashMap<>();
                    weekMap.put(0, getString(R.string.sun));
                    weekMap.put(1, getString(R.string.mon));
                    weekMap.put(2, getString(R.string.tue));
                    weekMap.put(3, getString(R.string.wed));
                    weekMap.put(4, getString(R.string.thu));
                    weekMap.put(5, getString(R.string.fri));
                    weekMap.put(6, getString(R.string.sat));

                    weeksStr = "";
                    for (int i = 0; i < 7; i++) {
                        if (whichWeeks[i].equals("true")) {
                            weeksStr += weekMap.get(i) + " ";
                        }
                    }

                    repeatStr += "; " + weeksStr;
                    break;
                case 3:
                    repeatStr += getString(R.string.repeat_every_month);
                    if (repeatMode.getSameDayOrSameWeekOfTheMonth() == 0) {
                        repeatStr += "; " + getString(R.string.same_day);
                    } else if (repeatMode.getSameDayOrSameWeekOfTheMonth() == 1) {
                        repeatStr += ";" + getString(R.string.same_week);
                    }
                    break;
                case 4:
                    repeatStr += getString(R.string.repeat_every_year);
                    break;
            }

            if (repeatMode.getEndCondition() == 1) {
                //直到某一个日期
                repeatStr += "; " + String.format(getString(R.string.end_condition_until), repeatMode.getEndDateTime());
            } else if (repeatMode.getEndCondition() == 2) {
                //直到一定次数
                repeatStr += "; " + String.format(getString(R.string.end_condition_for), repeatMode.getEndCounts() + "");
            }

            repeatModeTV.setText(repeatStr);

            //label
            labelTV.setText(event.getTag().equals("") ? getString(R.string.none) : event.getTag());

            //color
            colorTV.setText(colorNames[event.getColor()]);

            //isActive
            isActiveTV.setText(event.getIsActive() ? getString(R.string.enabled) : getString(R.string.disabled));

        } else {
            dismiss();
        }

        final PreviewEventListener listener = (PreviewEventListener) getActivity();

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setView(view);

        builder.setPositiveButton(getString(R.string.save), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                listener.onConfirmSaveEvent();
                dismiss();
            }
        }).setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dismiss();
            }
        }).setTitle(R.string.preview);

        return builder.create();
    }

    private String dateTimeToLocal(String dateTimeStr) {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault());

        Date datetime = null;
        try {
            datetime = dateFormat.parse(dateTimeStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(datetime);

        String year = new SimpleDateFormat("yyyy", Locale.getDefault()).format(calendar.getTime());
        String month = new SimpleDateFormat("MM", Locale.getDefault()).format(calendar.getTime());
        String day = new SimpleDateFormat("dd", Locale.getDefault()).format(calendar.getTime());
        String week = new SimpleDateFormat("E", Locale.getDefault()).format(calendar.getTime());
        String hour = new SimpleDateFormat("HH", Locale.getDefault()).format(calendar.getTime());
        String minute = new SimpleDateFormat("mm", Locale.getDefault()).format(calendar.getTime());

        String dateStr = String.format(getResources().getString(R.string.default_date_picker), week, month, day, year);
        String timeStr = String.format(getResources().getString(R.string.default_time_picker), hour, minute);

        return dateStr + " " + timeStr;
    }
}
